<template>
  <ContainerGroup id="containerGroup">
    <Container>
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        :button-list="buttonList"
        @submit="handerSearch"
        @reset="handleReset"
      />
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY" style="margin-top:8px">
      <OperationContainer>
        <Button icon="add" style="margin: 0" @click="_addItemHandle">新增</Button>
      </OperationContainer>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#FAFAFA', height: '42px' }"
        stripe
        size="mini"
        highlight-current-row
        is-fill-height
        height="0"
        style="margin-top: 10px;margin-left: 5px;"
        @sort-change="handleSortChange"
      >
        <el-table-column type="index" align="center" width="50" label="序号" />
        <el-table-column label="账号" prop="userName" show-overflow-tooltip />
        <el-table-column label="姓名" prop="realName" show-overflow-tooltip />
        <el-table-column label="角色" prop="roleId" sortable="custom" show-overflow-tooltip>
          <!-- <template slot-scope="scope">
            {{ getRoleName(scope.row) }}
          </template>-->
        </el-table-column>
        <el-table-column label="科室" prop="deptName" sortable="custom" show-overflow-tooltip />
        <el-table-column label="职务" prop="appointment" sortable="custom" show-overflow-tooltip />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <Tooltip content="编辑" icon="edit" @click="_editItemHandle(scope.row)" />
            <Tooltip content="删除" icon="delete" @click="_delItemHandle(scope.row)" />
            <Tooltip content="初始化密码" icon="refresh" @click="handleInitPwd(scope.row)" />
            <Tooltip content="权限分配" icon="operation" @click="handleQxFp(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right;">
        <el-pagination
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <Dialog
        :title="formtitle"
        :visible="dialogVisible"
        :footer-btns="[
          {
            text: '确定',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '关闭',
            type: 'info',
            trigger: 'cancel',
          }
        ]"
        @cancel="_cancel('ruleForm')"
        @confirm="submitForm('ruleForm')"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          style="top:0"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="ruleForm.username" size="mini" style="width:320px" />
          </el-form-item>
          <el-form-item label="姓名" prop="realname">
            <el-input v-model="ruleForm.realname" size="mini" style="width:320px" />
          </el-form-item>
          <el-form-item label="角色" prop="roleCode">
            <el-select
              v-model="ruleForm.roleCode"
              placeholder="请选择角色"
              size="mini"
              style="width:320px"
              multiple
              filterable
              clearable
            >
              <el-option
                v-for="item in filterElements[2].options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="deptCode">
            <el-select
              v-model="ruleForm.deptCode"
              placeholder="请选择部门"
              size="mini"
              style="width:320px"
              filterable
              clearable
            >
              <el-option
                v-for="item in dptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="职务">
            <el-input v-model="ruleForm.appointment" size="mini" style="width:320px" />
          </el-form-item>
          <el-form-item v-if="userstate === '1'" label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password" size="mini" style="width:320px" />
          </el-form-item>
          <el-form-item v-if="userstate === '1'" label="确认密码" prop="confirmpwd">
            <el-input
              v-model="ruleForm.confirmpwd"
              type="password"
              size="mini"
              style="width:320px"
            />
          </el-form-item>
        </el-form>
      </Dialog>
      <Drawer
        :visible="tableDialog"
        title="科室权限分配"
        :footer-btns="[
          {
            text: '确定',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          }
        ]"
        width="400px"
        @cancel="tableDialog = false"
        @confirm="handleQxConfirm"
      >
        <div class="tree-content">
          <!-- <div class="label-check">
            <label>11111</label>
            <el-checkbox v-model="checked" />
          </div>-->
          <div class="detail">
            <div class="list">
              <el-tree
                ref="depTree"
                :key="mathKey"
                v-loading="treeLoading"
                :data="dptqxList"
                node-key="deptCode"
                check-strictly
                :props="defaultProps"
                default-expand-all
                :expand-on-click-node="true"
              >
                <span slot-scope="{ node, data }" class="custom-tree-node">
                  <span @click="getNode(node)">{{ data.deptName }}</span>
                  <span style="position: absolute; right: 35px">
                    <el-checkbox v-model="node.checked" @change="getCharges(node, data)" />
                  </span>
                </span>
              </el-tree>
            </div>
          </div>
        </div>
      </Drawer>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  getSysUserList,
  updateSysUserDeptCode,
  getSysUserDeptCodeList,
  reStartPassword,
  getDepartment,
  insertSysUserManager,
  updateSysUser,
  getById,
  deleteById,
  getSysRoles,
  getCostDepartment,
  getSysRolesAll
} from '../../utils/apis/userManager/index'
import { getCostDepartments } from '@/utils/apis/accountingUnit/corres'
export default {
  name: 'UserManagement', // 用户管理
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.confirmpwd !== '') {
          this.$refs.ruleForm.validateField('confirmpwd')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      mathKey: '',
      treeLoading: false,
      defaultProps: {
        children: 'childrens',
        label: 'deptName'
      },
      tableDialog: false,
      dptqxList: [],
      dptList: [],
      loading: true,
      tableColumns: [
        {
          title: '账号',
          width: '',
          dataIndex: 'username'
        },
        {
          title: '工号',
          width: '',
          dataIndex: 'employeeId'
        },
        {
          title: '姓名',
          dataIndex: 'realname',
          width: ' '
        },
        {
          title: '性别',
          dataIndex: 'sexName',
          width: '80'
        },

        {
          title: '科室',
          dataIndex: 'deptName',
          value: ''
        },
        {
          title: '任职名称',
          dataIndex: 'dutyName',
          width: '180'
        },
        {
          title: '联系方式',
          dataIndex: 'phone',
          value: ''
        },
        {
          title: '角色',
          dataIndex: 'roleName',
          value: ''
        },
        {
          title: '账号状态',
          type: 'switch',
          dataIndex: 'enable',
          width: '180',
          handlerClick: this._handleSwitch
        },
        {
          title: '操作',
          render: [
            {
              label: '编辑',
              type: 'primary',
              handlerClick: this._editItemHandle
            },

            {
              label: '删除',
              type: 'primary',
              handlerClick: this._delItemHandle
            }
          ]
        }
      ],
      buttonList: [
        {
          label: '查询',
          type: 'primary',
          handlerClick: this.handerSearch
        },
        {
          label: '重置',
          type: 'info',
          handlerClick: this._reset
        }
      ],

      filterElements: [
        {
          key: 'userName',
          type: 'Input',
          label: '账号',
          width: 260
        },

        {
          key: 'realName',
          type: 'Input',
          label: '姓名',
          width: 260
        },

        {
          key: 'roleCode',
          type: 'Select',
          label: '角色',
          itemLabel: 'roleName',
          itemValue: 'id',
          value: '',
          options: [],
          width: 260
        }
      ],
      dialogVisible: false,
      ruleForm: {
        deptCode: '', // 科室编码
        deptName: '', // 科室名称
        dutyName: '', // 职务名称
        enable: '1', // 0启用 1停用
        password: '', // 密码
        confirmpwd: '', // 确认密码
        phone: '', // 电话
        realname: '', // 真正名字
        roleCode: [], // 角色ID
        sexCode: '', // 性别编码(1男 2女 0未知)
        username: '', // 用户名
        employeeId: '', // 工号
        newPassword: '',
        appointment: '',
        deptCodeList: [] // 部门
        // enable1: false
      },
      rules: {
        dutyName: [
          { required: true, message: '请输入职务名称', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmpwd: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
        phone: [{ required: true, message: '请填写手机号码', trigger: 'blur' }],
        realname: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        username: [{ required: true, message: '请填写账号', trigger: 'blur' }],
        employeeId: [
          { required: true, message: '请填写工号', trigger: 'blur' }
        ],
        deptCode: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        roleCode: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        sexCode: [{ required: true, message: '请选择性别', trigger: 'change' }],
        appointment: [
          { required: true, message: '请输入职务名称', trigger: 'blur' }
        ]
      },
      userstate: '',
      pageNum: 1,
      number: '',
      name: '',
      status: '',
      role: '',
      sex: '',
      dept: '',
      deptList: [],
      total: 0,
      pageSize: 20,
      currentPage: 1,
      tableData: [],
      queryList: {},
      userId: '',
      formtitle: '新增用户'
    }
  },
  mounted() {
    // this._getData()
    this.getRoleSelect()
    this.getSelect()
  },
  methods: {
    handleSortChange({ column, prop, order }) {
      console.log(column, prop, order)
      if (prop === 'roleId') {
        // 角色
        if (order === 'ascending') {
          // 升序
          this._getData('ROLE_ID  asc')
        } else if (order === 'descending') {
          // 降序
          this._getData('ROLE_ID  DESC')
        }
      } else if (prop === 'deptName') {
        // 科室
        if (order === 'ascending') {
          // 升序
          this._getData('DEPT_CODE  asc')
        } else if (order === 'descending') {
          // 降序
          this._getData('DEPT_CODE  DESC')
        }
      } else if (prop === 'appointment') {
        // 职务
        if (order === 'ascending') {
          // 升序
          this._getData('APPOINTMENT  asc')
        } else if (order === 'descending') {
          // 降序
          this._getData('APPOINTMENT  DESC')
        }
      }
    },
    getNode() {},
    handleQxConfirm() {
      // let arrList = []
      // const qxList = [
      //   { deptCode: '0000', deptName: '全部' },
      //   ...this.dptqxList[0]?.childrens
      // ]
      // const funcodes = this.$refs.depTree.getCheckedKeys()
      // if (funcodes.length === 0) {
      //   this.$message.warning('请勾选科室')
      //   return
      // }
      // if (qxList.length === funcodes.length) {
      //   arrList = ['0000']
      // } else {
      //   arrList = funcodes.filter(item => item !== '0000')
      // }
      const funcodes = this.$refs.depTree.getCheckedKeys()
      if (funcodes.length === 0) {
        this.$message.warning('请勾选科室')
        return
      }

      updateSysUserDeptCode({
        // deptCodeList: arrList,
        deptCodeList: funcodes,
        userId: this.userId
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success('修改成功')
          this._getData()
          this.tableDialog = false
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    getSelect() {
      getCostDepartment().then(res => {
        if (res.data.code === 200) {
          this.dptqxList = [res.data.data]
        }
      })
    },
    // 反选全选
    reverseSelect(node) {
      if (node.level !== 1) {
        let count = 0
        node.parent.childNodes.map((item, index) => {
          if (item.checked) {
            count++
          }
        })
        if (count === node.parent.childNodes.length) {
          node.parent.checked = true
        } else {
          // node.parent.checked = false;
        }
        this.reverseSelect(node.parent)
      }
    },
    // 角色,权限关系
    getCharges(row, data) {
      this.setParentNodeChecked(row)
      this.reverseSelect(row)
      this.selecAll(row)
    },
    // 全选
    selecAll(row) {
      if (row.childNodes.length !== 0) {
        row.childNodes.map((item, index) => {
          item.checked = row.checked
          this.selecAll(item)
        })
      }
    },
    // 子节点选中同时选中选中父节点
    setParentNodeChecked(node) {
      if (node.checked) {
        if (node.parent && node.level) {
          node.parent.checked = true
          this.setParentNodeChecked(node.parent)
        }
      } else {
        this.removeParentNodeChecked(node)
      }
    },
    // 子节点为空时移除选中父节点
    removeParentNodeChecked(node) {
      if (node.parent && node.level) {
        const tempArr = node.parent.childNodes.filter(item => {
          return item.checked
        })
        if (!tempArr.length) {
          node.parent.checked = false
          this.removeParentNodeChecked(node.parent)
        }
      }
    },
    handleQxFp(row) {
      // 权限分配
      this.userId = row.id
      this.tableDialog = true
      this.mathKey = Math.random()
      getSysUserDeptCodeList({
        userId: row.id
      }).then(res => {
        if (res.data.code === 200) {
          // let detailDptList = []
          // if (res.data.data && res.data.data.includes('0000')) {
          //   const dptListArr = this.dptqxList[0]?.childrens.map(
          //     item => item.deptCode
          //   )
          //   detailDptList = ['0000', ...dptListArr]
          // } else {
          //   detailDptList = res.data.data
          // }
          const detailDptList = res.data.data
          this.$refs.depTree.setCheckedKeys(detailDptList || [])
          this.treeLoading = false
        }
      })
    },
    handleInitPwd(row) {
      this.$confirm({
        content: '您确定初始化密码',
        title: '温馨提示',
        okFn: res => {
          reStartPassword({
            id: row.id
          }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '初始化密码成功!'
              })
              this._getData()
            }
          })
        },
        cancelFn: res => {
          console.log('初始化密码取消')
        }
      })
    },
    handleReset() {},
    getRoleSelect() {
      getSysRolesAll().then(res => {
        if (res.data.code === 200) {
          this.filterElements[2].options = res.data.data
        }
      })
      getDepartment({
        deptCode: '',
        deptname: ''
      }).then(res => {
        if (res.data.code === 200) {
          this.dptList = res.data.data
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this._getData()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this._getData()
    },
    dialogConfirm() {},
    getRoleName(row) {
      let roleName = ''
      this.filterElements[2].options.forEach(item => {
        if (item.value === row.roleId) {
          roleName = item.label
        }
      })
      return roleName
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = { ...this.ruleForm }
          if (this.userstate === '1') {
            const addParams = {
              realName: params.realname,
              roleId: params.roleCode?.join(','),
              userName: params.username,
              userPassword: params.password,
              deptCode: params.deptCode,
              deptName: this.dptList.find(
                item => item.deptCode === params.deptCode
              )?.deptName,
              appointment: params.appointment
            }
            insertSysUserManager(addParams).then(res => {
              if (res.data.code === 200) {
                this.$message.success(res.data.message)
                this._getData()
                this.dialogVisible = false
                this.$refs[formName].resetFields()
              } else {
                this.$message.error(res.data.message)
                this.$refs[formName].resetFields()
              }
            })
          } else if (this.userstate === '2') {
            const updateParams = {
              id: this.userId,
              realName: params.realname,
              roleId: params.roleCode?.join(','),
              userName: params.username,
              deptCode: params.deptCode,
              deptName: this.dptList.find(
                item => item.deptCode === params.deptCode
              )?.deptName,
              appointment: params.appointment
            }
            updateSysUser(updateParams).then(res => {
              if (res.data.code === 200) {
                this.$message.success('修改成功')
                this._getData()
                this.dialogVisible = false
                this.$refs[formName].resetFields()
              } else {
                this.$message.error(res.data.message)
                this.$refs[formName].resetFields()
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    _cancel(formName) {
      this.dialogVisible = false
      this.$refs[formName].resetFields()
    },
    // 删除
    _delItemHandle(row) {
      this.$confirm({
        content: '是否确认删除该用户？',
        title: '温馨提示',
        okFn: res => {
          deleteById(row.id).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this._getData()
            }
          })
        },
        cancelFn: res => {
          console.log('取消')
        }
      })
    },
    // 查询
    handerSearch(val) {
      this.queryList = val
      this._getData()
    },
    // 获取用户列表
    _getData(type = '') {
      const params = {
        type: type,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        userName:
          this.queryList.userName === undefined ? '' : this.queryList.userName,
        realName:
          this.queryList.realName === undefined ? '' : this.queryList.realName,
        roleId:
          this.queryList.roleCode === undefined ? '' : this.queryList.roleCode
        // 还需要加角色id
      }
      getSysUserList(params).then(res => {
        if (res.data.code === 200) {
          this.loading = false
          this.tableData = res.data.data.list
          this.total = res.data.data.total
          console.log('this.total', this.total)
        }
      })
    },
    // 获取角色，科室列表
    _getroleList() {},
    // 新增用户
    _addItemHandle() {
      this.dialogVisible = true
      this.userstate = '1'
      this.formtitle = '新增用户'
    },
    // 编辑用户
    _editItemHandle(row) {
      this.formtitle = '编辑用户'
      this.dialogVisible = true
      this.userstate = '2'
      getById(row.id).then(res => {
        if (res.data.code === 200) {
          const form = res.data.data
          this.ruleForm = {
            realname: form.realName,
            roleCode: form.roleId?.split(','),
            username: form.userName,
            deptCode: form.deptCode,
            appointment: form.appointment
          }
          this.userId = res.data.data.id
        }
      })
    },
    handleSwitch(row) {
      if (row.enable === '0') {
        row.enable = '1'
      } else {
        row.enable = '0'
      }
      // editSysUser({ userId: row.userId, enable: row.enable }).then((res) => {
      //   if (res.data.code === 200) {
      //     // console.log(res.data)
      //   }
      // })
    },
    enableswith(enable) {
      if (enable === '0') {
        this.ruleForm.enable = '1'
      } else {
        this.ruleForm.enable = '0'
      }
    }
  }
}
</script>
<style lang="less" scoped>
// .demo-ruleForm{
//   width: 600px;
//   // display: flex;
//   flex-wrap: wrap;
//   justify-content: space-between;
// }
.tree-content {
  padding: 10px 15px;
  height: 100%;
  overflow: hidden;
  overflow: auto;
  .label-check {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 35px;
    cursor: pointer;
    border-bottom: 1px solid #eeee;
  }
  .list {
    position: absolute;
    left: 0;
    right: 0;
  }
  .detail {
    border: 1px solid rgba(232, 234, 237, 1);
    height: 100%;
    position: relative;
    overflow: auto;
  }

  .detail /deep/ .el-tree-node__content {
    border-bottom: 1px solid #e8eaed;
    height: 40px;
    position: relative;
  }

  .detail /deep/ .el-icon-caret-right:before {
    content: '\e6e0';
  }
}

.el-table {
  /deep/ th {
    padding: 0;
    height: 40px;
    background-color: #f5f7fa;
  }
  /deep/ td {
    padding: 0;
    height: 44px;
    /deep/ button {
      font-size: 14px;
    }
    /deep/ input {
      height: 28px;
    }
    /deep/ .el-select__caret {
      line-height: 28px;
    }
  }
}
.switchbox {
  display: inline-flex;
  align-items: center;
  position: relative;
  font-size: 14px;
  line-height: 20px;
  height: 20px;
  vertical-align: middle;
  span {
    margin: 0;
    position: relative;
    width: 40px;
    height: 20px;
    outline: 0;
    border-radius: 10px;
    box-sizing: border-box;
    background: #dcdfe6;
    transition: border-color 0.3s, background-color 0.3s;
    vertical-align: middle;
    display: inline-block;
    cursor: pointer;
  }
  .switchafter {
    position: absolute;
    top: 2px;
    border-radius: 100%;
    transition: all 0.3s;
    width: 16px;
    height: 16px;
    background-color: #fff;
  }
  .spanactive {
    background: #ffa712;
  }
  .switchafteractive {
    left: 55%;
  }
  .switchafteritem {
    left: 1.5px;
  }
}
/deep/ .ck-dialog-container.animate {
  top: 0 !important;
  width: 40%;
}
</style>
